/**
 * 
 */
package fr.toto.menuitem;

import java.awt.Component;
import java.nio.file.Path;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

import com.kokotchy.betaSeriesAPI.model.Episode;
import com.kokotchy.betaSeriesAPI.model.Show;

import fr.toto.constantes.Constantes;
import fr.toto.subtitles.Soutitre;
import fr.toto.subtitles.SoutitreSet;
import fr.toto.triseries.EpisodesSet;
import fr.toto.triseries.Regex;
import fr.toto.triseries.SeriesSet;

/**
 * @author tshepo
 * 
 */
public class MyPopupMenu extends JPopupMenu implements Constantes {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6384806506636576359L;
	private JSeparator sp = new JSeparator();
	private JMenu seriesMenu = new JMenu(MESSAGES.getString("ArchiveMenu"));
	private JMenu soutitresMenu = new JMenu(MESSAGES.getString("SubtitleMenu"));

	/**
	 * @throws HeadlessException
	 */
	public MyPopupMenu() {
		this.add(new JMenuItem("(Vide)"));
		this.add(sp);
		this.add(seriesMenu);
		this.add(new JSeparator());
		this.add(soutitresMenu);
		this.add(new BetaSeriesMenuItem());
		this.add(new EditPropertiesMenuItem());
		this.add(new CloseMenuItem());

	}

	public void generateMenu() {
		int i = 0;
		videMenu();
		MyMenu mm = null;
		for (Object ep : EpisodesSet.ListATraiter()) {
			if (ep instanceof Episode) {
				if (!((Episode) ep).isSeen() && !SeriesSet.isArchived(((Episode) ep).getShowUrl())) {
					Path p = Regex.getEpisodeFile((Episode) ep);
					if (p.getNameCount() > 1) {
						if (mm != null
								&& mm.getText().equalsIgnoreCase(
										p.getName(0).toString())) {
							mm.add((Episode) ep, p.subpath(1, p.getNameCount()));
						} else {
							mm = new MyMenu(p.getName(0).toString());
							this.insert(mm, i++);
							mm.add((Episode) ep, p.subpath(1, p.getNameCount()));
						}
					} else {
						this.insert(new MyMenuItem((Episode) ep, p), i++);
					}

				}
			}

		}
		optimize();
		listSerieGen();
		listSubGen();
	}

	private void listSerieGen() {
		
		seriesMenu.removeAll();
		for(Show s : SeriesSet.ArchivedShows()) {
			seriesMenu.add(new ArchivedShowMenuItem(s));
		}
		seriesMenu.setVisible(seriesMenu.getItemCount() != 0);
	}
	

	private void listSubGen() {
		soutitresMenu.removeAll();
		for (Object s : SoutitreSet.ListATraiter()) {
			if (s instanceof Soutitre) {
				soutitresMenu.add(new SoutitreMenuItem((Soutitre) s));
			}
		}
		soutitresMenu.setVisible(soutitresMenu.getItemCount() != 0);
		
			
	}


	private void videMenu() {
		while (this.getComponentIndex(sp) != 0) {
			this.remove(0);
		}
	}
	
	private void optimize() {
		for (int i = this.getComponentIndex(sp) - 1; i>=0 ; i--) {
			Component comp = this.getComponent(i);
			if (comp instanceof MyMenu) {
				MyMenu mm = (MyMenu) comp;
				if(mm.optimized()) {
					for(int j = mm.getItemCount() - 1; j>=0; j--) {
						insert(mm.getItem(j),i);
					}
					this.remove(mm);
				}
			}
		}
	}

}
